<?php

/**
 * Created by PhpStorm.
 * User: d7
 * Date: 2016/1/15
 * Time: 11:04
 */
class Redis_session_relation
{
    const SESSION_PREFIX = 'ci_session:';

    protected $redis_config = array();
    protected $redis;

    private static $self_redis;

    /**
     * Redis_session_relation constructor.
     * @param array $data
     * @example $data = array( 'redis' =>
     *                      array( 'host'=>'127.0.0.1','port'=>'6379','timeout'=>300,'session_relation'=>'pt_session'));
     */
    function __construct($data = array())
    {
        $this->redis_config = $data['redis'];
        $this->redis = $this->getRedis();
    }

    private function getRedis(){
        if(self::$self_redis and is_object(self::$redis)){
            return self::$self_redis;
        }
        $redis = new Redis();
        $redis->connect($this->redis_config['host'],$this->redis_config['port'],$this->redis_config['timeout']);
        if(isset($this->redis_config['password']))
            $redis->auth($this->redis_config['password']);
        return self::$self_redis=$redis;
    }

    /*function set_relation($user_id,$session_id){
        $this->redis->hSet($this->redis_config['session_relation'],$user_id,$session_id);
    }

    function get_relation($user_id){
        return $this->redis->hGet($this->redis_config['session_relation'],$user_id);
    }

    function get_session_id($user_id){
        return self::SESSION_PREFIX.$this->get_relation($user_id);
    }*/

    function set_helpers($user_id,$users){
        return $this->redis->hSet('helper_online',$user_id,$users);
    }

    function get_helper($user_id=null){
        if($user_id==null){
            return $this->redis->hGetAll('helper_online');
        }else{
            return $this->redis->hGet('helper_online',$user_id);
        }
    }
}